<?php

namespace app\rental\service;

use app\rental\model\RentalCarModel;
use app\rental\model\RentalCategoryModel;
use app\admin\model\NavMenuModel;
use think\Db;
use think\Request;

class ApiService
{
    /**
     * 功能:查询汽车列表,支持分页;<br>     *
     * @param array $param 查询参数<pre>
     * array(
     *  'category_ids'=>'',
     *  'where'=>'',
     *  'limit'=>'',
     *  'order'=>'',
     *  'page'=>'',
     *  'relation'=>''
     * )
     * 字段说明:
     * category_ids:汽车所在分类,可指定一个或多个分类id,以英文逗号分隔,如1或1,2,3 默认值为全部
     * field:调用指定的字段
     *  limit:数据条数,默认值为10,可以指定从第几条开始,如3,8(表示共调用8条,从第3条开始)
     * order:排序方式,
     * where:查询条件,字符串形式,和sql语句一样,请在事先做好安全过滤,最好使用第二个参数$where的数组形式进行过滤,此方法查询时关联多个表,所以最好指定一下表名,以防字段冲突,查询条件(只支持数组),格式和thinkPHP的where方法一样,此方法查询时关联多个表,所以最好指定一下表名,以防字段冲突;
     * </pre>
     * @return array 包括分页的汽车列表<pre>
     * 格式:
     * array(
     *     "cars"=>array(),//汽车列表,array
     *     "page"=>"",//生成的分页html,不分页则没有此项
     *     "total"=>100, //符合条件的汽车总数,不分页则没有此项
     *     "total_pages"=>5 // 总页数,不分页则没有此项
     * )</pre>
     */
    public static function cars($param)
    {
        $rentalCarModel = new RentalCarModel();

        $where = [
            'post_status'    => 1,
            'delete_time'    => 0
        ];

        $paramWhere = empty($param['where']) ? '' : $param['where'];
        $field = !empty($param['field']) ? $param['field'] : '*';
        $limit       = empty($param['limit']) ? 10 : $param['limit'];
        $order       = empty($param['order']) ? '' : $param['order'];
        $page        = isset($param['page']) ? $param['page'] : false;
        $relation    = empty($param['relation']) ? '' : $param['relation'];
        $categoryIds = empty($param['category_ids']) ? '' : $param['category_ids'];

        if (!empty($categoryIds)) {
            if (!is_array($categoryIds)) {
                $categoryIds = explode(',', $categoryIds);
            }
            if (count($categoryIds) == 1) {
                $where['category_id'] = $categoryIds[0];
            } else {
                $where['category_id'] = ['in', $categoryIds];
            }
        }
        $cars = $rentalCarModel->alias('car')->field($field)
            ->where($where)
            ->where($paramWhere)
            ->order($order);

        $return = [];

        if (empty($page)) {
            $cars = $cars->limit($limit)->select();
            if (!empty($relation) && !empty($cars['items'])) {
                $cars->load($relation);
            }

            $return['cars'] = $cars;
        } else {
            if (is_array($page)) {
                if (empty($page['list_rows'])) {
                    $page['list_rows'] = 10;
                }

                $cars = $cars->paginate($page);
            } else {
                $cars = $cars->paginate(intval($page));
            }

            if (!empty($relation) && !empty($cars['items'])) {
                $cars->load($relation);
            }

            $cars->appends(request()->param());

            $return['cars']    = $cars->items();
            $return['page']        = $cars->render();
            $return['total']       = $cars->total();
            $return['total_pages'] = $cars->lastPage();
        }
        return $return;
    }

    /**
     * 获取指定id的汽车
     * @param int $id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    public static function car($id)
    {
        $rentalCarModel = new PortalPostModel();

        $where = [
            'published_time' => [['> time', 0], ['<', time()]],
            'post_status'    => 1,
            'post_type'      => 1,
            'id'             => $id,
            'delete_time'    => 0
        ];

        return $rentalCarModel->where($where)->find();
    }

    /**
     * 返回指定分类
     * @param int $id 分类id
     * @return array 返回符合条件的分类
     */
    public static function category($id)
    {
        $rentalCategoryModel = new RentalCategoryModel();

        $where = [
            'status'      => 1,
            'delete_time' => 0,
            'id'          => $id
        ];

        return $rentalCategoryModel->where($where)->find();
    }
    public static function footernavs($nav_id)
    {
        $navMenuModel = new NavMenuModel();
        $where = [
            'status'      => 1,
            'nav_id'      => $nav_id
        ];
       // dump($where);
        $navMenus= $navMenuModel->where($where)->select()->toArray();
        foreach ($navMenus as $key => $navMenu) {
            $href    = htmlspecialchars_decode($navMenu['href']);
            $hrefOld = $href;

            if (strpos($hrefOld, "{") !== false) {
                $href = json_decode($navMenu['href'], true);
                $href = cmf_url($href['action'], $href['param']);
            } else {
                if ($hrefOld == "home") {
                    $href = Request::instance()->root() . "/";
                } else {
                    $href = $hrefOld;
                }
            }
            $navMenus[$key]['href'] =$href;
        }

            //dump(self::arrToTree($navMenus->toArray(),0));
        return self::arrToTree($navMenus, 0);
    }
     //将数组转化为树形数组
    private static function arrToTree($data, $pid)
    {
        $tree = array();
        foreach ($data as $k => $v) {
            if ($v['parent_id'] == $pid) {
                $v['sub'] = self::arrToTree($data, $v['id']);
                $tree[] = $v;
            }
        }
        return $tree;
    }

    /**
     * 返回指定分类下的子分类
     * @param int $categoryId 分类id
     * @return false|\PDOStatement|string|\think\Collection 返回指定分类下的子分类
     */
    public static function subCategories($categoryId)
    {
        $rentalCategoryModel = new RentalCategoryModel();

        $where = [
            'status'      => 1,
            'delete_time' => 0,
            'parent_id'   => $categoryId
        ];

        return $rentalCategoryModel->where($where)->select();
    }

    /**
     * 返回指定分类下的所有子分类
     * @param int $categoryId 分类id
     * @return array 返回指定分类下的所有子分类
     */
    public static function allSubCategories($categoryId)
    {
        $rentalCategoryModel = new RentalCategoryModel();

        $categoryId = intval($categoryId);

        if ($categoryId !== 0) {
            $category = $rentalCategoryModel->field('path')->where('id', $categoryId)->find();

            if (empty($category)) {
                return [];
            }

            $categoryPath = $category['path'];
        } else {
            $categoryPath = 0;
        }

        $where = [
            'status'      => 1,
            'delete_time' => 0,
            'path'        => ['like', "$categoryPath-%"]
        ];

        return $rentalCategoryModel->where($where)->select();
    }

    /**
     * 返回符合条件的所有分类
     * @param array $param 查询参数<pre>
     * array(
     *  'where'=>'',
     *  'order'=>'',
     * )</pre>
     * @return false|\PDOStatement|string|\think\Collection
     */
    public static function categories($param)
    {
        $paramWhere = empty($param['where']) ? '' : $param['where'];

        $order = empty($param['order']) ? '' : $param['order'];

        $rentalCategoryModel = new RentalCategoryModel();

        $where = [
            'status'      => 1,
            'delete_time' => 0,
        ];

        return $rentalCategoryModel
            ->where($where)
            ->where($paramWhere)
            ->order($order)
            ->select();
    }
}
